import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';

class StatisticsPage extends StatelessWidget {
  final Map<String, List<bool>> dailyTasks;
  final List<String> taskTitles;

  const StatisticsPage({
    super.key, 
    required this.dailyTasks,
    required this.taskTitles,
  });

  String _dateToString(DateTime date) {
    return '${date.year}-${date.month}-${date.day}';
  }

  // 保存统计数据到文件
  Future<void> _saveStatistics(BuildContext context) async {
    try {
      // 获取下载目录
      final directory = Directory('/storage/emulated/0/Download');
      if (!await directory.exists()) {
        throw Exception('无法访问下载目录');
      }

      // 创建文件名（包含时间戳）
      final now = DateTime.now();
      final fileName = 'task_statistics_${now.year}${now.month}${now.day}_${now.hour}${now.minute}.txt';
      final file = File('${directory.path}/$fileName');

      // 准备写入的内容
      final StringBuffer content = StringBuffer();
      content.writeln('任务统计报告 (生成时间: ${now.year}年${now.month}月${now.day}日 ${now.hour}:${now.minute})');
      content.writeln('过去90天的任务完成情况：\n');

      // 获取过去90天的日期
      final List<DateTime> dates = List.generate(90, (index) {
        return DateTime.now().subtract(Duration(days: index));
      });

      // 生成每天的统计数据
      for (var date in dates) {
        final dateKey = _dateToString(date);
        int completedCount = 0;
        if (dailyTasks.containsKey(dateKey)) {
          completedCount = dailyTasks[dateKey]!
              .where((completed) => completed)
              .length;
        }
        double completionRate = (completedCount / taskTitles.length) * 100;

        content.writeln('${date.year}年${date.month}月${date.day}日:');
        // 如果完成率为0，跳过这一天
        if (completedCount == 0) {
          content.writeln(''); // 空行分隔
          continue;
        }

        content.writeln('完成率: ${completionRate.toStringAsFixed(1)}%');
        content.writeln('完成 $completedCount / ${taskTitles.length} 项任务');
        
        // 如果有完成的任务，列出具体完成了哪些任务
        // if (completedCount > 0 && dailyTasks.containsKey(dateKey)) {
        //   content.writeln('已完成的任务:');
        //   for (int i = 0; i < taskTitles.length; i++) {
        //     if (dailyTasks[dateKey]![i]) {
        //       content.writeln('- ${taskTitles[i]}');
        //     }
        //   }
        // }
        // 如果未完成的任务，列出具体未完成的任务
        if (completedCount < taskTitles.length && dailyTasks.containsKey(dateKey)) {
          content.writeln('未完成的任务:');
          for (int i = 0; i < taskTitles.length; i++) {
            if (!dailyTasks[dateKey]![i]) {
              content.writeln('- ${taskTitles[i]}');
            }
          }
        }
        content.writeln(''); // 空行分隔
      }

      // 写入文件
      await file.writeAsString(content.toString());

      // 显示成功消息
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('统计数据已保存到手机的下载文件夹: $fileName'),
            duration: const Duration(seconds: 3),
          ),
        );
      }
    } catch (e) {
      // 显示错误消息
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('保存失败: $e'),
            backgroundColor: Colors.red,
            duration: const Duration(seconds: 3),
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    // 获取过去90天的日期
    final List<DateTime> dates = List.generate(90, (index) {
      return DateTime.now().subtract(Duration(days: index));
    });

    return Scaffold(
      appBar: AppBar(
        title: const Text('任务统计'),
        backgroundColor: Theme.of(context).colorScheme.primaryContainer,
        actions: [
          // 添加保存按钮
          IconButton(
            icon: const Icon(Icons.save),
            onPressed: () => _saveStatistics(context),
            tooltip: '保存统计数据',
          ),
        ],
      ),
      body: ListView.builder(
        itemCount: dates.length,
        itemBuilder: (context, index) {
          final date = dates[index];
          final dateKey = _dateToString(date);
          
          // 计算当天任务完成率
          int completedCount = 0;
          if (dailyTasks.containsKey(dateKey)) {
            completedCount = dailyTasks[dateKey]!
                .where((completed) => completed)
                .length;
          }
          
          double completionRate = (completedCount / taskTitles.length) * 100;

          return Container(
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Colors.grey[200]!,
                  width: 1,
                ),
              ),
            ),
            child: ListTile(
              title: Row(
                children: [
                  // 日期显示
                  Text(
                    '${date.month}月${date.day}日',
                    style: const TextStyle(
                      fontSize: 16,
                    ),
                  ),
                  const SizedBox(width: 16),
                  // 进度条
                  Expanded(
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(4),
                      child: LinearProgressIndicator(
                        value: completionRate / 100,
                        minHeight: 10,
                        backgroundColor: Colors.grey[200],
                      ),
                    ),
                  ),
                  const SizedBox(width: 16),
                  // 完成率文字
                  Text(
                    '${completionRate.toStringAsFixed(0)}%',
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
              // 显示具体完成数量
              subtitle: Text(
                '完成 $completedCount / ${taskTitles.length} 项任务',
                style: TextStyle(
                  color: Colors.grey[600],
                  fontSize: 12,
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}
